package pers.xukai.fullMark.config.scheduleTask;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import pers.xukai.common.constant.GlobalConstant;
import pers.xukai.common.utils.email.EmailUtils;
import pers.xukai.fullMark.entity.bo.EmailTaskBo;

import java.util.Date;
import java.util.Map;
import java.util.Set;


@Slf4j
@Component
public class EmailTask {
    private final RedisTemplate<String, EmailTaskBo> redisTemplate;

    private EmailTask(RedisTemplate<String,EmailTaskBo> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Scheduled(cron = "0 0/1 * * * ?")
    public void configureTasks() {
        Date now = new Date();
        //{"email$task$":{userId:EmailTaskBo}}
        String redisKey = GlobalConstant.REDIS_KEY_EMAIL_TASK + DateUtil.format(new Date(), "yyyyMMdd");
        Set<Map.Entry<Object, Object>> entries = redisTemplate
                .opsForHash()
                .entries(redisKey).entrySet();
        for (Map.Entry<Object, Object> entry : entries) {
            String key = (String) entry.getKey();
            EmailTaskBo emailTaskBo = (EmailTaskBo) entry.getValue();
//            log.info(String.format("用户【%s】 时间【%s】 内容【%s】 邮件地址【%s】",emailTaskBo.getUserName(),emailTaskBo.getDate(),emailTaskBo.getTodoContent(),emailTaskBo.getEmailAddress()));
            Date userTodoDate = emailTaskBo.getDate();
            String todoContent = emailTaskBo.getTodoContent();
            String userName = emailTaskBo.getUserName();
            String emailAddress = emailTaskBo.getEmailAddress();
            if (!userTodoDate.after(now)) {
                EmailUtils.sendEmail(emailAddress, GlobalConstant.EMAIL_REMINDERS_TO_DO, todoContent);
                redisTemplate
                        .opsForHash()
                        .delete(redisKey, key);
                log.info("向用户{}发送了邮件",userName);
            }
        }
    }
}
